
// ==UserScript==
// @name         juejin-publish-ontime
// @namespace    juejin-publish-ontime
// @version      0.0.0
// @include      *
// @run-at       document-end
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_notification
// ==/UserScript==
(function () {
  'use strict';

  function styleInject(css, ref) {
    if ( ref === void 0 ) ref = {};
    var insertAt = ref.insertAt;

    if (!css || typeof document === 'undefined') { return; }

    var head = document.head || document.getElementsByTagName('head')[0];
    var style = document.createElement('style');
    style.type = 'text/css';

    if (insertAt === 'top') {
      if (head.firstChild) {
        head.insertBefore(style, head.firstChild);
      } else {
        head.appendChild(style);
      }
    } else {
      head.appendChild(style);
    }

    if (style.styleSheet) {
      style.styleSheet.cssText = css;
    } else {
      style.appendChild(document.createTextNode(css));
    }
  }

  var css_248z = ".global-module_popup__3o70v {\n  position: relative;\n}\n\n.global-module_panel__3ZbPQ {\n  position: absolute;\n  margin: 1.8rem -3rem 0 0;\n  top: 100%;\n  right: 0;\n  font-size: 1.2rem;\n  white-space: nowrap;\n  color: #909090;\n  background-color: #fff;\n  border: 1px solid #ddd;\n  border-radius: 2px;\n  -webkit-box-shadow: 0 1px 2px #f1f1f1;\n  box-shadow: 0 1px 2px #f1f1f1;\n  cursor: default;\n  z-index: 100;\n  display: none;\n  padding: 1em;\n}\n\n.global-module_show__1oPv5 {\n  display: block;\n}\n\n.global-module_picker__27fKo {\n  border: none;\n  outline: 0;\n  color: #deebfc;\n}\n\n.global-module_actionBar__3he2h {\n  margin-top: 1em;\n  display: flex;\n  gap: 1em;\n}\n\n.global-module_actionBar__3he2h > * {\n  flex: 1;\n}\n";
  var style = {"popup":"global-module_popup__3o70v","panel":"global-module_panel__3ZbPQ","show":"global-module_show__1oPv5","picker":"global-module_picker__27fKo","actionBar":"global-module_actionBar__3he2h"};
  styleInject(css_248z);

  const storageKey = "juejin-publish-ontime/record";
  const scheduleTimeStorageKey = "juejin-publish-ontime/timer";
  const tasks = GM_getValue(storageKey, {});

  function inEditor(pathname) {
    return /\/editor\/drafts(?:\/|$)/.test(pathname);
  }

  function getDraftByPath(pathname) {
    var _pathname$match;

    return ((_pathname$match = pathname.match(/\/editor\/drafts\/\d+(?:\/|$)/)) === null || _pathname$match === void 0 ? void 0 : _pathname$match[0]) || "";
  }

  function formatDate(dateInstance) {
    const year = dateInstance.getFullYear();
    const month = (dateInstance.getMonth() + 1).toString().padStart(2, "0");
    const date = dateInstance.getDate().toString().padStart(2, "0");
    const hour = dateInstance.getHours().toString().padStart(2, "0");
    const minutes = dateInstance.getMinutes().toString().padStart(2, "0");
    return `${year}-${month}-${date}T${hour}:${minutes}`;
  }

  function scheduler() {
    const current = new Date().getTime();
    const currentTasks = Object.entries(tasks).filter(_ref => {
      let [, time] = _ref;
      return time <= current;
    });
    currentTasks.forEach(_ref2 => {
      let [draft] = _ref2;
      delete tasks[draft];
    });
    GM_setValue(storageKey, tasks);
    currentTasks.forEach(_ref3 => {
      let [draft] = _ref3;
      GM_notification({
        title: "掘金定时发文提醒",
        text: "可以发布掘金文章了",
        onclick: () => {
          window.open(draft);
        }
      });
    });
    currentTasks.length = 0;
    const scheduleTime = GM_getValue(scheduleTimeStorageKey, 0);
    const duration = 60 * 1000;

    if (scheduleTime + duration < current) {
      GM_setValue(scheduleTimeStorageKey, current);
      setTimeout(() => {
        scheduler();
      }, duration);
    }
  }

  scheduler();

  function mount() {
    const publishBtn = document.querySelector(".markdown-editor > .editor-header > .right-box > .publish-popup");

    if (publishBtn) {
      var _publishBtn$parentEle;

      const popup = document.createElement("div");
      popup.classList.add(style.popup);
      const onTimeBtn = document.createElement("button");
      onTimeBtn.className = "xitu-btn xitu-btn-outline";
      onTimeBtn.textContent = getDraftByPath(location.href) in tasks ? "已定时" : "定时发布";
      const timePickerPanel = document.createElement("div");
      timePickerPanel.classList.add(style.panel);
      const dateTimePicker = document.createElement("input");
      dateTimePicker.type = "datetime-local";
      dateTimePicker.classList.add(style.picker);
      const actionBar = document.createElement("div");
      actionBar.classList.add(style.actionBar);
      const confirmBtn = document.createElement("button");
      confirmBtn.className = "xitu-btn";
      confirmBtn.textContent = "确定";
      confirmBtn.addEventListener("click", () => {
        try {
          const selectedTime = dateTimePicker.value;
          const time = new Date(selectedTime).getTime();

          if (!isNaN(time)) {
            const draft = getDraftByPath(location.href);

            if (draft) {
              tasks[draft] = time;
            }

            GM_setValue(storageKey, tasks);
            onTimeBtn.textContent = "已定时";
            timePickerPanel.classList.remove(style.show);
          }
        } catch (e) {}
      });
      const cancelBtn = document.createElement("button");
      cancelBtn.className = "xitu-btn xitu-btn-outline";
      cancelBtn.textContent = "取消";
      cancelBtn.addEventListener("click", () => {
        timePickerPanel.classList.remove(style.show);
      });
      actionBar.appendChild(cancelBtn);
      actionBar.appendChild(confirmBtn);
      timePickerPanel.appendChild(dateTimePicker);
      timePickerPanel.appendChild(actionBar);
      onTimeBtn.addEventListener("click", () => {
        timePickerPanel.classList.toggle(style.show);
        dateTimePicker.min = formatDate(new Date());
        dateTimePicker.value = formatDate(new Date());
      });
      popup.appendChild(onTimeBtn);
      popup.appendChild(timePickerPanel);
      (_publishBtn$parentEle = publishBtn.parentElement) === null || _publishBtn$parentEle === void 0 ? void 0 : _publishBtn$parentEle.insertBefore(popup, publishBtn);
    } else {
      setTimeout(mount, 1000);
    }
  }

  var main = {
    onLoaded() {
      if (inEditor(location.pathname)) {
        mount();
      }
    },

    onRouteChange(_prev, current) {
      if (inEditor(current)) {
        mount();
      }
    }

  };

  return main;

})();
